import requests
import json
import time
import random

# 请求地址
url = "https://push2his.eastmoney.com/api/qt/stock/kline/get"

# 请求头
headers = {
    "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/136.0.0.0 Safari/537.36"
}

# 查询参数
timestamp = int(time.time() * 1000)  # 当前时间戳
cb_value = f"jQuery{random.randint(10000000000000000000, 99999999999999999999)}_{timestamp}"

params = {
    "cb": cb_value,                                  # 随机生成的 JSONP 回调函数名
    "secid": "1.000001",                             # 股票的ID
    "ut": "fa5fd1943c7b386f172d6893dbfba10b",       # 用户标识
    "fields1": "f1,f2,f3,f4,f5,f6",                  # 主数据字段
    "fields2": "f51,f52,f53,f54,f55,f56,f57,f58,f59,f60,f61",  # 额外数据字段
    "klt": "101",                                    # K线图类型
    "fqt": "1",                                      # 前复权
    "beg": "20240101",                                      # 开始日期
    "end": "20501231",                               # 结束日期
    "smplmt": "1040.6",                              # 限制参数
    "lmt": "1000000",                                # 数据限制数量
    "_": str(timestamp)                              # 当前时间戳
}

# 发送请求
try:
    response = requests.get(url, headers=headers, params=params)
    if response.status_code == 200:
        data = response.text  # 直接获取文本数据
        print(data)  # 输出返回的原始数据

        # 保存数据到本地文件
        with open('stock_data(1-000001).txt', 'w', encoding='utf-8') as f:
            f.write(data)  # 将原始数据写入文件

        print("数据已保存到 stock_data(1-000001).txt")
    else:
        print(f"请求失败，状态码：{response.status_code}")
except requests.exceptions.RequestException as e:
    print(f"请求发生错误: {e}")